<?php

/* 店铺控制器 */
class StoreApp extends BackendApp
{
    var $_store_mod;

    function __construct()
    {
        $this->StoreApp();
    }

    function StoreApp()
    {
        parent::__construct();
        $this->_store_mod =& m('store');
    }

    function index()
    {
        $conditions = empty($_GET['wait_verify']) ? "state <> '" . STORE_APPLYING . "'" : "state = '" . STORE_APPLYING . "'";
        $filter = $this->_get_query_conditions(array(
            array(
                'field' => 'store_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'sgrade',
            ),
        ));
        $owner_name = trim($_GET['owner_name']);
        if ($owner_name)
        {

            $filter .= " AND (user_name LIKE '%{$owner_name}%' OR owner_name LIKE '%{$owner_name}%') ";
        }
        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
                $sort  = 'sort_order';
                $order = '';
            }
        }
        else
        {
            $sort  = 'store_id';
            $order = 'desc';
        }

        $this->assign('filter', $filter);
        $conditions .= $filter;
        $page = $this->_get_page();
        $stores = $this->_store_mod->find(array(
            'conditions' => $conditions,
            'join'  => 'belongs_to_user',
            'fields'=> 'this.*,member.user_name',
            'limit' => $page['limit'],
            'count' => true,
            'order' => "$sort $order"
        ));
        $sgrade_mod =& m('sgrade');
        $grades = $sgrade_mod->get_options();
        $this->assign('sgrades', $grades);
        
        $states = array(
            STORE_APPLYING  => LANG::get('wait_verify'),
            STORE_OPEN      => Lang::get('open'),
            STORE_CLOSED    => Lang::get('close'),
        );
        foreach ($stores as $key => $store)
        {
            $stores[$key]['sgrade'] = $grades[$store['sgrade']];
            $stores[$key]['state'] = $states[$store['state']];
            $certs = empty($store['certification']) ? array() : explode(',', $store['certification']);
            for ($i = 0; $i < count($certs); $i++)
            {
                $certs[$i] = Lang::get($certs[$i]);
            }
            $stores[$key]['certification'] = join('<br />', $certs);
        }
        $this->assign('stores', $stores);
        $page['item_count'] = $this->_store_mod->getCount();
        $this->import_resource(array('script' => 'inline_edit.js'));
        $this->_format_page($page);
        $this->assign('filtered', $filter? 1 : 0); //是否有查询条件
        $this->assign('page_info', $page);

        $this->display('store.index.html');
    }

//
//    //测试html转PDF
//    function pdf(){
//        require_once '../includes/mpdf/mpdf.php';
//        try{
//            $mpdf=new \mPDF('zh-cn','A4', 0, '宋体', 0, 0);
//
//            $html="<p style=\"text-align: center; width:1200px;\">
//    <span style=\";font-size:15px;font-family:STSongStd-Light-Acro;color:rgb(0,0,0)\"><span style=\"color: rgb(0, 0, 0); font-size: 20px; font-family: 黑体, SimHei;\">个人网络版客户管理及咨询服务协议&nbsp;</span></span>
//</p>
//<p>
//    <span style=\";font-size:15px;font-family:STSongStd-Light-Acro;color:rgb(0,0,0)\">保密等级：【机密】</span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">甲方： 【天津智信通电子商务有限公司】</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">地址： 【天津市河西区 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">大沽南路与琼州道交口东南侧恒华大厦2号楼1门2109-1-5】&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">乙方： 【注册人】&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">1、 概述&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">1.1 【Cloud-Moda】APP及微信小程 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">序：指由【天津智信通电子商务有限公司】 一家跨境电商进口零售平台公司自行开发设计的手机，电脑应用程序，甲方拥 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">有授权范围的相关权益并享受本协议项下相关服务。&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">1.2 乙方渠道客户：凡受乙方销售渠道影响而成为APP和微信小程序用 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">户并实现最终交易的客户均视为乙方渠道客户，包括：&nbsp; &nbsp;（1）通过乙方进行扫码、关注直接成为APP和微信小程序上消费者 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">的客户；&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">2、 双方权利义务 甲乙双方开展合作，由乙方向甲方提供客户管理及咨询服务，甲方向乙方支付相关服务费用。 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">甲乙双方在合作中的具体权利义务如下：</span>
//</p>
//<p>
//    <span style=\"font-family: STSongStd-Light-Acro; font-size: 15px;\">2.1 甲方的权利义务：&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">2.1.1甲方为乙方配置APP和微信小程序平台唯一识别编码， </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">用以统计通过乙方客户管理服务所带来的销售收入，并且以乙方渠道编码在APP和微信小程序平台上的实收销售额作为乙方 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">客户管理服务事项的结算依据，甲方的结算技术统计系统的数据采集原理等应当向乙方进行合理披露并通过该系统实现数据 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">查询功能；&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">2.1.2甲方保证其提供的素材合法，内容不违反国家的有关政策，不侵犯第三方权利人的合法权益；&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">3、 结算及支</span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">付&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">3.1 结算依据：甲方根据乙方服务进行业绩计算，乙方服务费以APP和微信小程序实收销售额的【5】%进行结算，作为服 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">务费向乙方进行支付。&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">3.2 结算及支付周期如下：&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">3.2.1结算及付款：双方以甲方提供的数据为结算依据。 每个账单区间为每 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">月21日（含）到下月的20日（含）（但首个账单区间为合作开始日至第一个20日），再下个月的5号由甲方向乙方出具账单， </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">同月最后一日由甲方向乙方支付服务费。若出具账单日或者付款日为法定节假日或休息日，则顺延到下一个工作日。&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">4、 合</span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">作期限 4.1 双方首次合作期【6】个月，自双方正式开始合作日起算，到期运营正常合同可顺延。&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">5、 售后条款以及权益&nbsp;</span>
//</p>
//<p>
//    <span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.1 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">甲方对该APP和微信小程序内售卖商品质量进行管控，自行承担产品质量责任，因销售产品引起的质量问题由甲方承担相关 </span><span style=\"font-size: 15px; font-family: STSongStd-Light-Acro;\">退货、调换、赔偿等法律责任。 甲方对此协议有最终解释权。&nbsp;</span>
//</p>
//<p  style=\"text-align: center; width:1200px;\">
//    <span>————此行以下无正文————</span>
//    <img src=\"http://cloud-moda.com/ueditor/php/upload/image/20200908/1599556840390538.png\" title=\"1599556840390538.png\" alt=\"09e7b0b5f50f3a0b6ea5d63b709c40d.png\" style=\"width: 1px; height: 1px;\" width=\"1\" height=\"1\"/><img src=\"http://cloud-moda.com/ueditor/php/upload/image/20200908/1599556899136443.png\" title=\"1599556899136443.png\" alt=\"图片.png\" style=\"width: 135px; height: 130px;\" width=\"135\" height=\"130\"/>
//</p>
//";
//
//            $html = str_replace('margin-left:100px;', '', $html);// es
//            //7.0 写法
//            //        $mpdf = new \mPDF(['utf-8', 'A4', 16, '', 10, 10, 15, 1]);
//            $mpdf->SetDisplayMode('fullpage');
//            $mpdf->autoScriptToLang = true;
//            $mpdf->autoLangToFont = true;
//
//            $mpdf->WriteHTML($html);
//
//            $mpdf->Output(); //直接输出到页面
//
//            $fileName='个人网络版客户管理及咨询服务协议 .pdf'; //保存到文件
//            $mpdf->Output($fileName);
//
//        }catch (Exception $e){
//            return false;
//        }
//    }




    function test()
    {

        if (!IS_POST)
        {
            $sgrade_mod =& m('sgrade');
            $grades = $sgrade_mod->find();
            if (!$grades)
            {
                $this->show_warning('set_grade_first');
                return;
            }
            $this->display('store.test.html');
        }
        else
        {
            $user_name = trim($_POST['user_name']);
            $password  = $_POST['password'];

            /* 连接到用户系统 */
            $ms =& ms();
            $user = $ms->user->get($user_name, true);
            if (empty($user))
            {
                $this->show_warning('user_not_exist');
                return;
            }
            if ($_POST['need_password'] && !$ms->user->auth($user_name, $password))
            {
                $this->show_warning('invalid_password');

                return;
            }

            $store = $this->_store_mod->get_info($user['user_id']);
            if ($store)
            {
                if ($store['state'] == STORE_APPLYING)
                {
                    $this->show_warning('user_has_application');
                    return;
                }
                else
                {
                    $this->show_warning('user_has_store');
                    return;
                }
            }
            else
            {
                header("Location:index.php?app=store&act=add&user_id=" . $user['user_id']);
            }
        }
    }

    function add()
    {

        $user_id = $_GET['user_id'];
        if (!$user_id)
        {
            $this->show_warning('Hacking Attempt');
            return;
        }

        if (!IS_POST)
        {
            /* 取得会员信息 */
            $user_mod =& m('member');
            $user = $user_mod->get_info($user_id);
            $this->assign('user', $user);

            $this->assign('store', array('state' => STORE_OPEN, 'recommended' => 0, 'sort_order' => 65535, 'end_time' => 0));

            $sgrade_mod =& m('sgrade');
            $this->assign('sgrades', $sgrade_mod->get_options());

            $this->assign('states', array(
                STORE_OPEN   => Lang::get('open'),
                STORE_CLOSED => Lang::get('close'),
            ));

            $this->assign('recommended_options', array(
                '1' => Lang::get('yes'),
                '0' => Lang::get('no'),
            ));

            $this->assign('scategories', $this->_get_scategory_options());

            $region_mod =& m('region');
            $this->assign('regions', $region_mod->get_options(0));
            
            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js,mlselection.js'
            ));
            $this->assign('enabled_subdomain', ENABLED_SUBDOMAIN);
            $this->display('store.form.html');
        }
        else
        {

            /* 检查名称是否已存在 */
            if (!$this->_store_mod->unique(trim($_POST['store_name'])))
            {
                $this->show_warning('name_exist');
                return;
            }




            $domain = empty($_POST['domain']) ? '' : trim($_POST['domain']);
            if (!$this->_store_mod->check_domain($domain, Conf::get('subdomain_reserved'), Conf::get('subdomain_length')))
            {
                $this->show_warning($this->_store_mod->get_error());

                return;
            }
            $data = array(
                'store_id'     => $user_id,
                'store_name'   => $_POST['store_name'],
                'owner_name'   => $_POST['owner_name'],
                'owner_card'   => $_POST['owner_card'],
                'region_id'    => $_POST['region_id'],
                'region_name'  => $_POST['region_name'],
                'address'      => $_POST['address'],
                'zipcode'      => $_POST['zipcode'],
                'tel'          => $_POST['tel'],
                'sgrade'       => $_POST['sgrade'],
                'end_time'     => empty($_POST['end_time']) ? 0 : gmstr2time(trim($_POST['end_time'])),
                'state'        => $_POST['state'],
                'recommended'  => $_POST['recommended'],
                'sort_order'   => $_POST['sort_order'],
                'add_time'     => gmtime(),
                'domain'       => $domain,
            );

            $certs = array();
            isset($_POST['autonym']) && $certs[] = 'autonym';
            isset($_POST['material']) && $certs[] = 'material';
            $data['certification'] = join(',', $certs);

            if ($this->_store_mod->add($data) === false)
            {
                $this->_drop_store_image($user_id); // 注意这里要先删除图片，再删除店铺，因为删除图片时要查店铺信息
                $this->_store_mod->drop($user_id);
                $this->show_warning($this->_store_mod->get_error());
                return false;
            }else{
                $this->admin_log("新增店铺[".$_POST['store_name']."]",1);
            }

//            lichen 2019/4/22 start
//            $post_data = array(
//                "Name"=>$_POST['store_name'], //店铺名称
//                "ExternCode"=>$user_id, //店铺编号
//                "Address"=>$_POST['address'],//店铺地址
//                "Active"=>"0"//店铺状态
//            );
//            $url = ERP_URL; #url 地址必须 http://xxxxx
//            $res = $this->sync_data($url,$post_data);
//            if($res['MessageCode'] != 1){
//                $this->_drop_store_image($user_id); // 注意这里要先删除图片，再删除店铺，因为删除图片时要查店铺信息
//                $this->_store_mod->drop($user_id);
//                $this->show_warning($res['ErrorMsg']);
//                return false;
//            }

//            lichen 2019/4/22 end


            $this->_store_mod->unlinkRelation('has_scategory', $user_id);
            $cate_id = intval($_POST['cate_id']);
            if ($cate_id > 0)
            {
                $this->_store_mod->createRelation('has_scategory', $user_id, $cate_id);
            }
            $this->show_message('add_ok',
                'back_list',    'index.php?app=store',
                'continue_add', 'index.php?app=store&amp;act=test'
            );
        }
    }

    function edit()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!IS_POST)
        {
            /* 是否存在 */
            $store = $this->_store_mod->get_info($id);
            if (!$store)
            {
                $this->show_warning('store_empty');
                return;
            }
            if ($store['certification'])
            {
                $certs = explode(',', $store['certification']);
                foreach ($certs as $cert)
                {
                    $store['cert_' . $cert] = 1;
                }
            }
            $this->assign('store', $store);

            $sgrade_mod =& m('sgrade');
            $this->assign('sgrades', $sgrade_mod->get_options());

            $this->assign('states', array(
                STORE_OPEN   => Lang::get('open'),
                STORE_CLOSED => Lang::get('close'),
            ));

            $this->assign('recommended_options', array(
                '1' => Lang::get('yes'),
                '0' => Lang::get('no'),
            ));

            $region_mod =& m('region');
            $this->assign('regions', $region_mod->get_options(0));
            
            $this->assign('scategories', $this->_get_scategory_options());

            $scates = $this->_store_mod->getRelatedData('has_scategory', $id);
            $this->assign('scates', array_values($scates));

            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js,mlselection.js'
            ));
            $this->assign('enabled_subdomain', ENABLED_SUBDOMAIN);
            $this->display('store.form.html');
        }
        else
        {
            /* 检查名称是否已存在 */
            if (!$this->_store_mod->unique(trim($_POST['store_name']), $id))
            {
                $this->show_warning('name_exist');
                return;
            }
            $store_info = $this->_store_mod->get_info($id);

//            lichen 2019/5/10 start
            if($store_info['sync_state'] != 2){
                $this->show_warning('OMS尚未绑定');
                return;
            }
//            lichen 2019/5/10 start
            $domain = empty($_POST['domain']) ? '' : trim($_POST['domain']);
            if ($domain && $domain != $store_info['domain'])
            {
                if (!$this->_store_mod->check_domain($domain, Conf::get('subdomain_reserved'), Conf::get('subdomain_length')))
                {
                    $this->show_warning($this->_store_mod->get_error());

                    return;
                }
            }

            $data = array(
                'store_name'   => $_POST['store_name'],
                'owner_name'   => $_POST['owner_name'],
                'owner_card'   => $_POST['owner_card'],
                'region_id'    => $_POST['region_id'],
                'region_name'  => $_POST['region_name'],
                'address'      => $_POST['address'],
                'zipcode'      => $_POST['zipcode'],
                'tel'          => $_POST['tel'],
                'sgrade'       => $_POST['sgrade'],
                'end_time'     => empty($_POST['end_time']) ? 0 : gmstr2time(trim($_POST['end_time'])),
                'state'        => $_POST['state'],
                'sort_order'   => $_POST['sort_order'],
                'recommended'  => $_POST['recommended'],
                'domain'       => $domain,
            );
            $data['state'] == STORE_CLOSED && $data['close_reason'] = $_POST['close_reason'];
            $certs = array();
            isset($_POST['autonym']) && $certs[] = 'autonym';
            isset($_POST['material']) && $certs[] = 'material';
            $data['certification'] = join(',', $certs);

            $old_info = $this->_store_mod->get_info($id); // 修改前的店铺信息
            $this->_store_mod->edit($id, $data);

            $this->_store_mod->unlinkRelation('has_scategory', $id);
            $cate_id = intval($_POST['cate_id']);
            if ($cate_id > 0)
            {
                $this->_store_mod->createRelation('has_scategory', $id, $cate_id);
            }

            /* 如果修改了店铺状态，通知店主 */
            if ($old_info['state'] != $data['state'])
            {
                $ms =& ms();
                if ($data['state'] == STORE_CLOSED)
                {
                    // 关闭店铺
                    $subject = Lang::get('close_store_notice');
                    //$content = sprintf(Lang::get(), $data['close_reason']);
                    $content = get_msg('toseller_store_closed_notify',array('reason' => $data['close_reason']));
                }
                else
                {
                    // 开启店铺
                    $subject = Lang::get('open_store_notice');
                    $content = Lang::get('toseller_store_opened_notify');
                }
                $ms->pm->send(MSG_SYSTEM, $old_info['store_id'], '', $content);
                $this->_mailto($old_info['email'], $subject, $content);
            }
            
            $this->admin_log(Lang::get('edit_store'),1);

            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->show_message('edit_ok',
                'back_list',    'index.php?app=store&page=' . $ret_page,
                'edit_again',   'index.php?app=store&amp;act=edit&amp;id=' . $id
            );
        }
    }

    //异步修改数据
   function ajax_col()
   {
       $id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
       $column = empty($_GET['column']) ? '' : trim($_GET['column']);
       $value  = isset($_GET['value']) ? trim($_GET['value']) : '';
       $data   = array();
       if (in_array($column ,array('recommended','sort_order')))
       {
           $data[$column] = $value;
           $this->_store_mod->edit($id, $data);
           if(!$this->_store_mod->has_error())
           {
               echo ecm_json_encode(true);
           }
       }
       else
       {
           return ;
       }
       return ;
   }

    function drop()
    {
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$id)
        {
            $this->show_warning('no_store_to_drop');
            return;
        }

        $ids = explode(',', $id);
        if(count($ids)>1 && !$_GET['wait_verify']){
            $this->show_warning('不能进行批量删除操作');
            return;
        }
        $order_mod=& m('order');
        $member_mod=& m('member');
        $refund_mod=& m('refund');
        $member_mod->db->query('start transaction');
        foreach ($ids as $id)
        {
            
            //判断店铺是否有未完成的订单
            if($order_mod->get('seller_id='.$id.' AND status NOT IN('.ORDER_FINISHED.','.ORDER_CANCELED.')')){
                $member_mod->db->query('rollback');
                $this->show_warning('该店铺有未完成订单，请等待订单完成后操作');
                return;
            }
            //是否有处理中的退款
            if($refund_mod->get('seller_id='.$id.' AND status NOT IN("SUCCESS","CLOSED","FAILED")')){
                $member_mod->db->query('rollback');
                $this->show_warning('该店铺有未完成退款，请等待退款完成后操作');
                return;
            }
            //判断店主冻结余额是否为0
            $member=$member_mod->get($id);
            if($member['money_dj'] != 0){
                $member_mod->db->query('rollback');
                $this->show_warning('该店主冻结金额不为0，不能进行操作');
                return;
            }
            
            $this->_drop_store_image($id); // 注意这里要先删除图片，再删除店铺，因为删除图片时要查店铺信息
        }
        if (!$this->_store_mod->drop($ids))
        {
            $member_mod->db->query('rollback');
            $this->show_warning($this->_store_mod->get_error());
            return;
        }
        $member_mod->db->query('commit');
        $this->admin_log(Lang::get('del_store'),1);

        /* 通知店主 */
        $user_mod =& m('member');
        $users = $user_mod->find(array(
            'conditions' => "user_id" . db_create_in($ids),
            'fields'     => 'user_id, user_name, email',
        ));
        foreach ($users as $user)
        {
            $ms =& ms();
            $subject = Lang::get('drop_store_notice');
            $content = get_msg('toseller_store_droped_notify');
            $ms->pm->send(MSG_SYSTEM, $user['user_id'], $subject, $content);
            $this->_mailto($user['email'], $subject, $content);
        }
        
        $this->show_message('drop_ok');
    }

    /* 更新排序 */
    function update_order()
    {
        if (empty($_GET['id']))
        {
            $this->show_warning('Hacking Attempt');
            return;
        }

        $ids = explode(',', $_GET['id']);
        $sort_orders = explode(',', $_GET['sort_order']);
        foreach ($ids as $key => $id)
        {
            $this->_store_mod->edit($id, array('sort_order' => $sort_orders[$key]));
        }

        $this->show_message('update_order_ok');
    }

    /* 查看并处理店铺申请 */
    function view()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!IS_POST)
        {
            /* 是否存在 */
            $store = $this->_store_mod->get_info($id);
            if (!$store)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $sgrade_mod =& m('sgrade');
            $sgrades = $sgrade_mod->get_options();
            $store['sgrade'] = $sgrades[$store['sgrade']];
            $this->assign('store', $store);

            $scates = $this->_store_mod->getRelatedData('has_scategory', $id);
            $this->assign('scates', $scates);

            $this->display('store.view.html');
        }
        else
        {
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            /* 批准 */

            if (isset($_POST['agree']))
            {

//              lichen 2019/4/22 start
                $store_info = $this->_store_mod->get_info($id);
                $post_data = array(
                    "Name"=>$store_info['store_name'], //店铺名称
                    "ExternCode"=>$id, //店铺编号
                    "Address"=>$store_info['address'],//店铺地址
                    "Active"=>"0"//店铺状态
                );
                $url = ERP_URL; #url 地址必须 http://xxxxx
                $res = $this->sync_data($url,$post_data);
                if($res['MessageCode'] != 1) {
                    $this->show_warning($res['ErrorMsg']);
                    return;
                }
//              lichen 2019/4/22 end
                $this->_store_mod->edit($id, array(
//                    lichen 2019/5/15 start
//                    'state'      => STORE_OPEN,
                    'state'      => STORE_CLOSED,
                    'sync_state' => 1,
//                    lichen 2019/5/15 end
                    'add_time'   => gmtime(),
                    'sort_order' => 65535,
                ));

                $content = get_msg('toseller_store_passed_notify');
                $ms =& ms();
                $ms->pm->send(MSG_SYSTEM, $id, '', $content);
                $store_info = $this->_store_mod->get_info($id);
                $this->send_feed('store_created', array(
                    'user_id'   =>  $store_info['store_id'],
                    'user_name'   => $store_info['user_name'],
                    'store_url'   => SITE_URL . '/' . url('app=store&id=' . $store_info['store_id']),
                    'seller_name'   => $store_info['store_name'],
                ));
                $this->_hook('after_opening', array('user_id' => $id));
                $this->admin_log(Lang::get('agree_apply'),1);
                $this->show_message('agree_ok',
                    'edit_the_store', 'index.php?app=store&amp;act=edit&amp;id=' . $id,
                    'back_list', 'index.php?app=store&wait_verify=1&page=' . $ret_page
                );
            }
            /* 拒绝 */
            elseif (isset($_POST['reject']))
            {
                $reject_reason = trim($_POST['reject_reason']);
                if (!$reject_reason)
                {
                    $this->show_warning('input_reason');
                    return;
                }

                $content = get_msg('toseller_store_refused_notify', array('reason' => $reject_reason));
                $ms =& ms();
                $ms->pm->send(MSG_SYSTEM, $id, '', $content);

                $this->_drop_store_image($id); // 注意这里要先删除图片，再删除店铺，因为删除图片时要查店铺信息
                $this->_store_mod->drop($id);
                $this->admin_log(Lang::get('Rejection_store_application'),1);
                $this->show_message('reject_ok',
                    'back_list', 'index.php?app=store&wait_verify=1&page=' . $ret_page
                );
            }
            else
            {
                $this->show_warning('Hacking Attempt');
                return;
            }
        }
    }

    function batch_edit()
    {
        if (!IS_POST)
        {
            $sgrade_mod =& m('sgrade');
            $this->assign('sgrades', $sgrade_mod->get_options());

            $region_mod =& m('region');
            $this->assign('regions', $region_mod->get_options(0));

            $this->headtag('<script type="text/javascript" src="{lib file=mlselection.js}"></script>');
            $this->display('store.batch.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $ids = explode(',', $id);
            $data = array();
            if ($_POST['region_id'] > 0)
            {
                $data['region_id'] = $_POST['region_id'];
                $data['region_name'] = $_POST['region_name'];
            }
            if ($_POST['sgrade'] > 0)
            {
                $data['sgrade'] = $_POST['sgrade'];
            }
            if ($_POST['certification'])
            {
                $certs = array();
                if ($_POST['autonym'])
                {
                    $certs[] = 'autonym';
                }
                if ($_POST['material'])
                {
                    $certs[] = 'material';
                }
                $data['certification'] = join(',', $certs);
            }
            if ($_POST['recommended'] > -1)
            {
                $data['recommended'] = $_POST['recommended'];
            }
            if (trim($_POST['sort_order']))
            {
                $data['sort_order'] = intval(trim($_POST['sort_order']));
            }

            if (empty($data))
            {
                $this->show_warning('no_change_set');
                return;
            }

            $this->_store_mod->edit($ids, $data);
            $this->admin_log(Lang::get('Bulk_editing_store'),1);
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->show_message('edit_ok',
                'back_list', 'index.php?app=store&page=' . $ret_page);
        }
    }

    function check_name()
    {
        $id         = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $store_name = empty($_GET['store_name']) ? '' : trim($_GET['store_name']);

        if (!$this->_store_mod->unique($store_name, $id))
        {
            echo ecm_json_encode(false);
            return;
        }
        echo ecm_json_encode(true);
    }

    /* 删除店铺相关图片 */
    function _drop_store_image($store_id)
    {
        $files = array();

        /* 申请店铺时上传的图片 */
        $store = $this->_store_mod->get_info($store_id);
        for ($i = 1; $i <= 3; $i++)
        {
            if ($store['image_' . $i])
            {
                $files[] = $store['image_' . $i];
            }
        }

        /* 店铺设置中的图片 */
        if ($store['store_banner'])
        {
            $files[] = $store['store_banner'];
        }
        if ($store['store_logo'])
        {
            $files[] = $store['store_logo'];
        }

        /* 删除 */
        foreach ($files as $file)
        {
            $filename = ROOT_PATH . '/' . $file;
            if (file_exists($filename))
            {
                @unlink($filename);
            }
        }
        //删除店铺的目录 , 此目录 存放店铺上传的图片和信息。
        $this->del_DirAndFile(ROOT_PATH."/data/files/store_".$store_id);
    }
    
    function del_DirAndFile($dirName) {
        if (is_dir($dirName)) {
            if ($handle = opendir("$dirName")) {
                while (false !== ( $item = readdir($handle) )) {
                    if ($item != "." && $item != "..") {
                        if (is_dir("$dirName/$item")) {
                            $this->del_DirAndFile("$dirName/$item");
                        } else {
                            if(strpos($item,'small_') === false && strpos($item,'spec_') === false){
                            unlink("$dirName/$item");
                            }
                        }
                    }
                }
                closedir($handle);
                //rmdir($dirName);
            }
        }
    }
    

    /* 取得店铺分类 */
    function _get_scategory_options()
    {
        $mod =& m('scategory');
        $scategories = $mod->get_list();
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');

        return $tree->getOptions();
    }


//    lichen 2019/4/22 start
    function sock_data($url,$port=80,$t=30,$method='get',$data=null)
    {
        $info=parse_url($url);
        $fp = fsockopen($info['host'],$port,$errno,$errstr,$t);

        // 判断是否有数据
        if(isset($data) && !empty($data))
        {
            $query = http_build_query($data); // 数组转url 字符串形式
        }else
        {
            $query=null;
        }
        // 如果用户的$url "http://www.manongjc.com/";  缺少 最后的反斜杠
        if(!isset($info['path']) || empty($info['path']))
        {
            $info['path']="/index.html";
        }
        // 判断 请求方式
        if($method=='post')
        {
            $head = "POST ".$info['path']." HTTP/1.0".PHP_EOL;
        }else
        {
            $head = "GET ".$info['path']."?".$query." HTTP/1.0".PHP_EOL;
        }

        $head .= "Host: ".$info['host'].PHP_EOL; // 请求主机地址
        $head .= "Referer: http://".$info['host'].':'.$port.$info['path'].PHP_EOL;
        if(isset($data) && !empty($data) && ($method=='post'))
        {
            $head .= "Content-type: application/x-www-form-urlencoded".PHP_EOL;
            $head .= "Content-Length: ".strlen(trim($query)).PHP_EOL;
            $head .= PHP_EOL;
            $head .= trim($query);
        }else
        {
            $head .= PHP_EOL;
        }
//        var_dump($head);exit;
        $write = fputs($fp, $head); //写入文件(可安全用于二进制文件)。 fputs() 函数是 fwrite() 函数的别名
        while (!feof($fp))
        {
            $line = fread($fp,4096);
            echo $line;
        }
    }

    function create_guid(){
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $uuid = substr($charid, 0, 8).'-'.substr($charid, 8, 4).'-'
            .substr($charid,12, 4).'-'.substr($charid,16, 4).'-'
            .substr($charid,20,12);
        return $uuid;
    }

    function sync_data($url, $data_string) {
        $data_string = json_encode($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if(!$res){
            return array('MessageCode'=>2, 'ErrorMsg'=>'同步失败');
        }else{
            return json_decode($res,true);
        }
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $return_content = ob_get_contents();
        ob_end_clean();

        return array('code'=>$return_code, 'result'=>$return_content);
    }
//    lichen 2019/4/22 end
}

?>
